package com.jeff.android.lab.module.media;

import android.Manifest;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.jeff.android.lab.BaseFragment;
import com.jeff.android.lab.R;
import com.jeff.permission.CheckPermission;
import com.jeff.permission.PermissionItem;
import com.jeff.permission.PermissionListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author: dingfeng
 * @date: 2020-01-13
 * @since: 1.0.0
 **/
public class VideoRecordFragment extends BaseFragment implements SurfaceHolder.Callback {

    @BindView(R.id.surface_view)
    SurfaceView mSurfaceView;

    @BindView(R.id.btn_start)
    Button btnStart;

    @BindView(R.id.btn_end)
    Button btnEnd;

    @BindView(R.id.iv_camera_orientation)
    ImageView iv_camera_orientation;

    MediaRecorder mMediaRecorder;
    Camera mCamera;
    int mCurrentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;


    private String[] permissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
    };

    @Override
    protected int getRootLayout() {
        return R.layout.media_fragment_video_record;
    }

    @Override
    protected void initView() {

        SurfaceHolder holder = mSurfaceView.getHolder();
        holder.addCallback(this);


        CheckPermission.instance(mContext).check(
                new PermissionItem(permissions), new PermissionListener() {
                    @Override
                    public void permissionGranted() {
                        Log.d(TAG, "permissionGranted ... ");
                        mCamera = Camera.open(mCurrentCameraId);
                    }

                    @Override
                    public void permissionDenied() {

                    }
                });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated ... ");
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d(TAG, "surfaceChanged ... ");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d(TAG, "surfaceDestroyed ... ");
    }

    @OnClick(R.id.btn_start)
    public void start() {
        try {
            if (prepareVideoRecorder()) {
                mMediaRecorder.start();
            }
        } catch (IOException e) {
        }
    }

    @OnClick(R.id.btn_end)
    public void stop() {
        mMediaRecorder.stop();
        releaseMediaRecorder();
        mCamera.lock();
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
    }

    @OnClick(R.id.iv_camera_orientation)
    public void switchCamera() {
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
        if (mCurrentCameraId == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            mCurrentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
        } else {
            mCurrentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
        }
        mCamera = Camera.open(mCurrentCameraId);//Camera.CameraInfo.CAMERA_FACING_BACK
    }

    /*
     * 相机预览前的准备工作代码 单独抽出来
     * */
    private boolean prepareVideoRecorder() throws IOException {
        if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.reset();
        }

        /*camera相关设置部分*/
        mCamera = Camera.open(mCurrentCameraId);//Camera.CameraInfo.CAMERA_FACING_BACK
        if (mCamera != null) {
            mCamera.unlock();
            mMediaRecorder.setCamera(mCamera);
        }

        /*recorder设置部分*/
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));

        mMediaRecorder.setOutputFile(getOutputMediaFile());
        mMediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface());
        mMediaRecorder.prepare();

        return true;
    }

    /*
     * 获取手机外部存储路径
     * */
    private String getOutputFile() {
        File mediaFile;
        boolean OutputExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (OutputExist) {
            mediaFile = Environment.getExternalStorageDirectory();
            return mediaFile.toString();
        }
        return null;
    }

    /*
     * 获取录制视频的日期 作为存储文件路径一部分
     * */
    private String getDate() {
        Log.d(TAG, "获取录制视频的日期 ");
        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);   // 获取年份
        int month = ca.get(Calendar.MONTH);   // 获取月份
        int day = ca.get(Calendar.DATE);   // 获取日
        String date = "" + year + "_" + (month + 1) + "_" + day;
        return date;
    }

    /*
     *创建视频存储文件夹 录制好的视频存储在手机外部存储中 以录像时间+mp4格式命名
     * */
    private String getOutputMediaFile() {
        Log.d(TAG, "获取视频存储的位置 ");
        String mediaPath = getOutputFile();
        if (mediaPath != null) {
            File mediaFile = new File(mediaPath + "/aaa");
            if (!mediaFile.exists()) {
                mediaFile.mkdir();
            }
            return mediaFile.getAbsolutePath() + File.separator + getDate() + ".mp4";
        }
        return null;
    }

    /*
     * 录制视频结束时释放相机资源
     * */
    private void releaseMediaRecorder() {
        Log.d(TAG, "录制结束后释放资源 ");
        if (mMediaRecorder != null) {
            mMediaRecorder.reset(); // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            mCamera.lock();   // lock camera for later use
        }
    }







    /**
     * View 转化为 Bitmap
     * @param view
     * @return bitmap
     */
    public static Bitmap view2Bitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);

        return bitmap;
    }


    /**
     * save bitmap to sdcard
     *
     * @param bitmap
     * @param path
     */
    public static void saveBitmap(Bitmap bitmap, String path) {
        File file = new File(path);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
